package com.github.cyf.common.validator;

import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author chenyifan
 * @create 2024-05-07 21:00
 */
public class EnumStringValidator implements ConstraintValidator<EnumString, Object> {
    private List<String> enumValues;
    private String type;
    private String msg;

    @Override
    public void initialize(EnumString annotation) {
        type = annotation.type();
        enumValues = Arrays.asList(annotation.value());
        msg = annotation.message();
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {
        if (obj == null || !enumValues.contains(obj.toString())) {
            setErrorMsg(obj, context);
            return false;
        }
        return true;
    }

    private void setErrorMsg(Object obj, ConstraintValidatorContext context) {
        // 如果注解的 msg 属性已经定义了错误信息，则直接返回，否则生成默认的错误信息
        if (StringUtils.hasText(msg)) {
            return;
        }
        if (!StringUtils.hasText(type)) {
            throw new IllegalArgumentException("EnumString注解type字段不能为空");
        }
        // 禁止默认消息返回
        context.disableDefaultConstraintViolation();
        // 自定义返回消息
        String customMsg;
        if (Objects.isNull(obj) || !StringUtils.hasText(obj.toString())) {
            customMsg = String.format("%s不能为空，只能为：【%s】", type, String.join(",", enumValues));
        } else {
            customMsg = String.format("%s不能为【%s】，只能为：【%s】", type, obj, String.join(",", enumValues));
        }
        context.buildConstraintViolationWithTemplate(customMsg).addConstraintViolation();
    }
}
